<?php
/*
 * 模块调用文件
 * 每个模块都需要调用的文件
 * @author     Mark <zhaody901@126.com>
 * @copyright  Copyright (c) 2013 lemon team
 * @version    $Id: f1679102b82c6ba63d534a21f10495572f63a938 $
 * @time       14-2-7 上午10:28
 */
defined('IN_IXDCW') or exit('Access Denied');

/**
 * 查看单条信息收费
 *      如果设置单条信息收费, 则按照单条信息收费
 *      如果收费小于0, 则免费
 *      如果等于0, 则按照模块收费
 * @param $item_fee
 * @param $mod_fee
 * @return int
 */
function get_fee($item_fee, $mod_fee) {
	if($item_fee < 0) {
		$fee = 0;
	} else if($item_fee == 0) {
		$fee = $mod_fee;
	} else {
		$fee = $item_fee;
	}
	return $fee;
}

/**
 * 关键词搜索更新
 * 有则更新,无则插入
 * @param $kw
 * @param $items
 * @param $moduleid
 */
function keyword($kw, $items, $moduleid) {
	global $db, $DT_TIME, $DT;

	if(!$DT['search_kw'] || $items < 2 || strlen($kw) < 3 || strlen($kw) > 30 || strpos($kw, ' ') !== false) return;
	$kw = addslashes($kw);
	$r = $db->getOne("SELECT * FROM {$db->getPre()}keyword WHERE moduleid=$moduleid AND word='$kw'");
	
	if($r) {
		$items        = $items > $r['items'] ? $items : $r['items'];
		$month_search = date('Y-m', $r['updatetime']) == date('Y-m', $DT_TIME) ? 'month_search+1' : '1';
		$week_search  = date('W', $r['updatetime']) == date('W', $DT_TIME) ? 'week_search+1' : '1';
		$today_search = date('Y-m-d', $r['updatetime']) == date('Y-m-d', $DT_TIME) ? 'today_search+1' : '1';
		$db->query("UPDATE {$db->getPre()}keyword SET items='$items',updatetime='$DT_TIME',total_search=total_search+1,month_search=$month_search,week_search=$week_search,today_search=$today_search WHERE itemid=$r[itemid]");
	} else {
		$letter = Str::text2py($kw);
		$status = $DT['search_check_kw'] ? 2 : 3;
		$db->query("INSERT INTO {$db->getPre()}keyword (moduleid,word,keyword,letter,items,updatetime,total_search,month_search,week_search,today_search,status) VALUES ('$moduleid','$kw','$kw','$letter','$items','$DT_TIME','1','1','1','1','$status')");
	}
}

/**
 * 更新资金数量
 * @param $username
 * @param $amount
 */
function money_add($username, $amount) {
	global $db;
	if($username && $amount) $db->query("UPDATE {$db->getPre()}member SET money=money+{$amount} WHERE username='$username'");
}

/**
 * 锁定资金
 * @param $username
 * @param $amount
 */
function money_lock($username, $amount) {
	global $db;
	if($username && $amount) $db->query("UPDATE {$db->getPre()}member SET locking=locking+{$amount} WHERE username='$username'");
}

/**
 * 发布信息扣款
 * @param $groupid
 * @param $userinfo
 * @param $areas
 * @param $moduleid
 * @return array/bool
 */
function push_charge($groupid,$userinfo,$areas,$moduleid) {
	global $db,$AREA,$MODULE;
	$module= $MODULE[$moduleid]['module'];
	$MG = PCache::read('group-'.$groupid.'.php');
	if($areas[0]==0){
		$areas = array();
		$citys = $db->getAll('select areaid from '.$db->getPre().'city ');
		foreach($citys as $v){
			$areas[] = $v['areaid'];
		}
	}
	if($areas && $MG['city_limits']!=3){
		if(isset($MG[$module.'_charge']) && $MG[$module.'_charge'] > 0){
			$city_num = 0;
			switch($MG['city_limits']){
				case 1://本地区免费
					foreach($areas as $v){
						if($v!= $userinfo['cityid']){
							$str = $db->count($db->getPre().'city','areaid='.$v);
							if($str)$city_num++;
						}
					}
					break;
				case 2://本省免费
					$preid = $AREA[$userinfo['cityid']]['parentid'] ? $AREA[$userinfo['cityid']]['parentid'] : $userinfo['cityid'];//用户所在省份id
					$area = explode(',',$AREA[$preid]['arrchildid']);
					foreach($areas as $v){
						if(!in_array($v,$area)){
							$str = $db->count($db->getPre().'city','areaid='.$v);
							if($str)$city_num++;
						}
					}
					break;
				default:
					foreach($areas as $v){
						$str = $db->count($db->getPre().'city','areaid='.$v);
						if($str)$city_num++;
					}
			}
		}
		$total = $MG[$module.'_charge'] * $city_num;
		if($userinfo['money']<$total){
			return array('success'=>false,'total'=>$total);
		}
		return array('success'=>true,'total'=>$total);
	}
	return array('success'=>true,'total'=>0);
}


/**
 * 资金日志
 * @param        $username  用户名
 * @param        $amount    数量
 * @param        $bank      银行
 * @param        $editor    编辑者
 * @param        $reason    事由
 * @param string $note      备注
 */
function money_record($username, $amount, $bank, $editor, $reason, $note = '') {
	global $db, $DT_TIME;
	if($username && $amount) {
		$r = $db->getOne("SELECT money FROM {$db->getPre()}member WHERE username='$username'");
		$balance = $r['money'];
		$db->query("INSERT INTO {$db->getPre()}finance_record (username,bank,amount,balance,addtime,reason,note,editor) VALUES ('$username','$bank','$amount','$balance','$DT_TIME','$reason','$note','$editor')");
	}
}

/**
 * 增加积分
 * @param $username     用户名
 * @param $amount       积分数量
 */
function credit_add($username, $amount) {
	global $db;
	if($username && $amount) $db->query("UPDATE {$db->getPre()}member SET credit=credit+{$amount} WHERE username='$username'");
}

/**
 * 增加积分的记录
 * @param $username         用户名称
 * @param $amount           数量
 * @param $editor           操作者
 * @param $reason           原因
 * @param string $note      备注
 */
function credit_record($username, $amount, $editor, $reason, $note = '') {
	global $db, $DT_TIME, $DT;
	if($DT['log_credit'] && $username && $amount) {
		$r = $db->getOne("SELECT credit FROM {$db->getPre()}member WHERE username='$username'");
		$balance = $r['credit'];
		$db->query("INSERT INTO {$db->getPre()}finance_credit (username,amount,balance,addtime,reason,note,editor) VALUES ('$username','$amount','$balance','$DT_TIME','$reason','$note','$editor')");
	}
}

/**
 * 增加金卡资金
 * @param $username     用户名
 * @param $amount       金卡资金
 */
function cardmoney_add($username, $amount) {
	global $db;

	if($username && $amount) $db->query("UPDATE {$db->getPre()}member SET cardmoney=cardmoney+{$amount} WHERE username='$username'");
}

/**
 * 增加金卡资金的记录
 * @param $username         用户名称
 * @param $amount           数量
 * @param $editor           操作者
 * @param $reason           原因
 * @param string $note      备注
 */
function cardmoney_record($username, $amount, $editor, $reason, $note = '') {
	global $db, $DT_TIME;
	if($username && $amount) {
		$r = $db->getOne("SELECT cardmoney FROM {$db->getPre()}member WHERE username='$username'");
		$balance = $r['cardmoney'];
		$db->query("INSERT INTO {$db->getPre()}finance_cardmoney (username,amount,balance,addtime,reason,note,editor) VALUES ('$username','$amount','$balance','$DT_TIME','$reason','$note','$editor')");
	}
}

/**
 * 添加短信可用数量
 * @param $username
 * @param $amount
 */
function sms_add($username, $amount) {
	global $db;
	if($username && $amount) $db->query("UPDATE {$db->getPre()}member SET sms=sms+{$amount} WHERE username='$username'");
}

/**
 * 短信日志
 * @param        $username  用户名
 * @param        $amount    数量
 * @param        $editor    编辑者
 * @param        $reason    事由
 * @param string $note      日志
 */
function sms_record($username, $amount, $editor, $reason, $note = '') {
	global $db, $DT_TIME;
	if($username && $amount) {
		$r = $db->getOne("SELECT sms FROM {$db->getPre()}member WHERE username='$username'");
		$balance = $r['sms'];
		$db->query("INSERT INTO {$db->getPre()}finance_sms (username,amount,balance,addtime,reason,note,editor) VALUES ('$username','$amount','$balance','$DT_TIME','$reason','$note','$editor')");
	}
}

/**
 * 秒数 -> 日期
 *   8000 -> 2小时13分20秒
 * @param $seconds
 * @return string
 */
function secondstodate($seconds) {
	include load('include.lang');
	$date = '';
	if($seconds > 0) {
		$t = floor($seconds/86400);
		if($t) {
			$date .= $t.$L['mod_day'];
			$seconds = $seconds%86400;
		}
		$t = floor($seconds/3600);
		if($t) {
			$date .= $t.$L['mod_hour'];
			$seconds = $seconds%3600;
		}
		$t = floor($seconds/60);
		if($t) {
			$date .= $t.$L['mod_minute'];
			$seconds = $seconds%60;
		}
		if($seconds) {
			$date .= $seconds.$L['mod_second'];
		}
	}
	return $date;
}

/**
 * @param $content      有待截取的内容
 * @param int $length   带截取的长度
 * @return mixed|string 截取内容的一部分
 */
function get_intro($content, $length = 0) {
	if($length) {
		$intro = trim(Str::trimEOL(strip_tags($content)));
		// 删除实体
		$intro = preg_replace("/&([a-z]{1,});/", '', $intro);
		return Str::cut($intro, $length);
	} else {
		return '';
	}
}

/**
 * 获取文章的描述
 * @param $content  内容
 * @param $length   截取的长度
 * @return string
 */
function get_description($content, $length) {
	if($length) {
		$content = str_replace(array(' ', '[pagebreak]'), array('', ''), $content);
		return nl2br(Str::cut(trim(strip_tags($content)), $length, '...'));
	} else {
		return '';
	}
}

/**
 * 获取模块设置
 * @param        $moduleid
 * @param string $key
 * @return array|mixed|string
 */
function get_module_setting($moduleid, $key = '') {
	$M = PCache::read('module-'.$moduleid.'.php');
	return $key ? $M[$key] : $M;
}

/**
 * 图片表现联系方式
 * @param $string
 * @return string
 */
function anti_spam($string) {
	global $MODULE, $DT;
	if($DT['anti_spam'] && preg_match("/^[a-z0-9_@\-\s\/\.\,\(\)\+]+$/i", $string)) {
		do {
			$tmp = Crypt::encode($string);
			if(strpos($tmp, '0x') === false) break;
		} while(1);
		return '<img src="'.$MODULE[3]['linkurl'].'image.php?auth='.rawurlencode($tmp).'" align="absmddle"/>';
	} else {
		return $string;
	}
}

/**
 * 隐藏IP
 * @param        $ip
 * @param string $sep
 * @return string
 */
function hide_ip($ip, $sep = '*') {
	if(!preg_match("/[\d\.]{7,15}/", $ip)) return $ip;
	$tmp = explode('.', $ip);
	return $tmp[0].'.'.$tmp[1].'.'.$sep.'.'.$sep;
}

/**
 * 隐藏账户名
 * @param        $name
 * @param string $sep
 * @return string
 */
function hide_name($name, $sep = '*') {
	$len = strlen($name);
	$str = '';
	for($i = 0; $i < $len; $i++) {
		$str .= ($i == 0 || $i == $len - 1) ? $name{$i} : $sep;
	}
	return $str;
}

/**
 * 收费有效时间.
 * @param $moduleid
 * @param $itemid
 * @return array|void
 */
function check_pay($moduleid, $itemid) {
	global $db, $_username, $DT_TIME, $MOD;
	// 检查是否付过费
	$condition = "moduleid=$moduleid AND itemid=$itemid AND username='$_username'";
	// 检查是否在付费期限内.
	if($MOD['fee_period']) $condition .= " AND paytime>".($DT_TIME - $MOD['fee_period']*60);
	return $db->getOne("SELECT itemid FROM {$db->getPre()}finance_pay WHERE $condition");
}

/**
 * 检测给定的sign是否和加密后的string相符
 * @param $string
 * @param $sign
 * @return bool
 */
function check_sign($string, $sign) {
	return $sign == crypt_sign($string);
}

/**
 * 字串签名加密, 根据IP和KEY进行二次MD5加密
 * @param $string
 * @return string
 */
function crypt_sign($string) {
	global $DT_IP;
	return strtoupper(md5(md5($DT_IP.$string.DT_KEY)));
}

/**
 * 缓存点击量
 * 将访问的itemid缓存进入文件中, 并不存入数据库
 * @param $moduleid
 * @param $itemid
 */
function cache_hits($moduleid, $itemid) {
	if(@$fp = fopen(DT_CACHE.'/hits-'.$moduleid.'.php', 'a')) {
		flock($fp, LOCK_EX);
		fwrite($fp, $itemid.' ');
		flock($fp, LOCK_UN);
		fclose($fp);
	}
}

/**
 * 将文件中的缓存点击数量存储到数据库中
 * 更新点击次数
 * @param $moduleid
 * @param $table
 */
function update_hits($moduleid, $table) {
	global $db, $DT_TIME;
	$hits = trim(File::get(DT_CACHE.'/hits-'.$moduleid.'.php'));
	File::put(DT_CACHE.'/hits-'.$moduleid.'.php', ' ');
	File::put(DT_CACHE.'/hits-'.$moduleid.'.dat', $DT_TIME);
	if($hits) {
		$tmp = array_count_values(explode(' ', $hits));
		$arr = array();
		foreach($tmp as $k=>$v) {
			$arr[$v] .= $k ? ','.$k : '';
		}
		$id = $moduleid == 4 ? 'userid' : 'itemid';
		foreach($arr as $k=>$v) {
			$db->query("UPDATE LOW_PRIORITY {$table} SET `hits`=`hits`+".$k." WHERE `$id` IN (0".$v.")", 'UNBUFFERED');
		}
	}
}

/**
 * 添加关联链接
 * @param $content  内容
 * @param $moduleid
 * @return mixed
 */
function keylink($content, $moduleid) {
	global $KEYLINK;
	$KEYLINK or $KEYLINK = PCache::read('keylink-'.$moduleid.'.php');
	if(!$KEYLINK) return $content;
	$data = $content;
	foreach($KEYLINK as $k=>$v) {
		$quote = str_replace(array("'", '-'), array("\'", '\-'), preg_quote($v['title']));
		// 是否匹配在标签之内
		$data = preg_replace('/(?!((<.*?)|(<a.*?)|(<strong.*?)))('.$quote.')(?!(([^<>]*?)>)|([^>]*?</a>)|([^>]*?</strong>))/si', '<a href="'.$v['url'].'" target="_blank"><strong class="keylink">'.$v['title'].'</strong></a>', $data, 1);
		if($data == '') $data = $content;
	}
	return $data;
}

/**
 * 返回性别的语言表示法
 * @param     $gender
 * @param int $type
 * @return mixed
 */
function gender($gender, $type = 0) {
	global $L;
	if($type) return $gender == 1 ? $L['man'] : $L['woman'];
	return $gender == 1 ? $L['sir'] : $L['lady'];
}

/**
 * 用户是否在线
 * @param $userid
 * @return int
 */
function online($userid) {
	global $db;
	$r = $db->getOne("SELECT online FROM {$db->getPre()}online WHERE userid=$userid");
	if($r) return $r['online'] ? 1 : -1;
	return 0;
}

/**
 * 修复链接地址, 如果没有 :// 则补齐
 * @param $url
 * @return string
 */
function fix_link($url) {
	if(strlen($url) < 10) return '';
	return strpos($url, '://') === false  ? 'http://'.$url : $url;
}

/**
 * vip 年份
 * @param $fromtime
 * @return int
 */
function vip_year($fromtime) {
	global $DT_TIME;
	return $fromtime ? intval(($DT_TIME - $fromtime)/86400/365) + 1 : 1;
}

/**
 * 获取相册
 * @param     $item
 * @param int $type
 *      0   -60px  缩略图
 *      1   -240px 240宽度图片
 * @return array
 */
function get_albums($item, $type = 0) {
	$imgs = array();
	if($type == 0) {
		$nopic =  CSSIMG_URL.'common/nopic60.gif';
		$imgs[] = $item['thumb'] ? $item['thumb'] : $nopic;
		$imgs[] = $item['thumb1'] ? $item['thumb1'] : $nopic;
		$imgs[] = $item['thumb2'] ? $item['thumb2'] : $nopic;
	} else if($type == 1) {
		$nopic = CSSIMG_URL.'common/nopic240.gif';
		$imgs[] = $item['thumb'] ? str_replace('.thumb.', '.middle.', $item['thumb']) : $nopic;
		$imgs[] = $item['thumb1'] ? str_replace('.thumb.', '.middle.', $item['thumb1']) : $nopic;
		$imgs[] = $item['thumb2'] ? str_replace('.thumb.', '.middle.', $item['thumb2']) : $nopic;
	}
	return $imgs;
}

/**
 * xml样式的linkurl
 * @param        $linkurl
 * @param string $modurl
 * @return mixed
 */
function xml_linkurl($linkurl, $modurl = '') {
	if(strpos($linkurl, '://') === false) $linkurl = linkurl($modurl).$linkurl;
	return str_replace('&', '&amp;', $linkurl);
}

/**
 * 添加高亮
 * @param $str
 * @return string
 */
function highlight($str) {
	return '<span class="highlight">'.$str.'</span>';
}
?>